package com.thjk.bdf.preloan.web.controller;


import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thjk.bdf.common.base.BasicResp;
import com.thjk.bdf.common.enmus.ProductEnum;
import com.thjk.bdf.common.entity.ApplyOrder;
import com.thjk.bdf.common.entity.SmsLog;
import com.thjk.bdf.common.utils.GenerateIdsUtil;
import com.thjk.bdf.preloan.web.config.AppConfig;
import com.thjk.bdf.preloan.web.config.BdFConfig;
import com.thjk.bdf.preloan.web.service.MisService;
import com.thjk.bdf.preloan.web.util.SeesionUtils;
import com.thjk.bdf.service.OrderService;
import com.thjk.bdf.service.SmsService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.hash.Hashing;

/**
 * 
 * @创建日期： 2019年11月4日
 * @author 束凯
 * @Description：贷款申请处理类，负责获取验证码，提交贷款申请
 */
@Controller
@RequestMapping("/loan")
public class LoanController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
    private SmsService smsService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private AppConfig appConfig;
	@Autowired
	private BdFConfig bdFConfig;
	@Autowired
	private MisService misService;
	
	/**
	 * 验证客户经理手机号
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="/custMngPhone", produces="application/json; charset=utf-8")
	@ResponseBody
	public String ajaxVerifyMgrPhone(HttpServletRequest request,HttpServletResponse response) {
		String phone = request.getParameter("phone");//手机号
		BasicResp resp = misService.phoneCheck(phone);
		return JSONObject.toJSONString(resp);
	}
	
	
	@RequestMapping(value="/getSmsCode",method= RequestMethod.GET)
	@ResponseBody
	public String getSmsCode(HttpServletRequest request,HttpServletResponse response){
		
		Map<String,Object> result = new HashMap<>();
		
		String phone = request.getParameter("phoneNo");//手机号
		String merchantName = request.getParameter("merchantName");//企业名称
		
		if(StringUtils.isEmpty(phone)){
			logger.info("--->>>未接收到有效的参数 phone不能为空。");
			return "common/error";
		}
		//校验手机是否正确
		BasicResp basicRsp = misService.phoneCheck(phone);
		if(!BasicResp.isSuccess(basicRsp)){
			logger.info("校验客户经理手机号："+JSON.toJSONString(basicRsp));
			result.put("isOldCus", false);
			result.put("success", false);
			result.put("message", basicRsp.getMessage());
			return JSONObject.toJSONString(result);
		}
		String ip = request.getParameter("ip");//ip地址
		String wifi = request.getParameter("wifi");//wifi地址
		
		
		// 获取短信smsCode
		SmsLog SmsLog = new SmsLog();
		SmsLog.setPhone(phone);
		SmsLog.setIp(ip);
		SmsLog.setWifi(wifi);
		SmsLog.setMsg(merchantName);
		BasicResp resp = smsService.sendSmsMsg(SmsLog);
		logger.info("短信发送结果："+JSON.toJSONString(resp));
		result.put("isOldCus", false);
		result.put("message", resp.getMessage());
		if(BasicResp.isSuccess(resp)){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		
		return JSONObject.toJSONString(result);
	}
	
	/**
	 * 
	 * @Description: 申请信息提交处理
	 * @params:参宿说明
	 */
	@PostMapping(value="/submitApply")
	@ResponseBody
	public String submitApply( Model model,HttpServletRequest request,HttpServletResponse response){
		try {
			//验证短信验证码
			String phone = request.getParameter("phoneNo");//手机号
			String smsCode = request.getParameter("captcha");//验证码
			String licenseNo = request.getParameter("licenseNo");//社会统一信用码
			String merchantName = request.getParameter("merchantName");//商户名
			SmsLog phoneInfo = new SmsLog();
			phoneInfo.setPhone(phone);
			phoneInfo.setSmsCode(smsCode);
			BasicResp resp = smsService.checkSmsMsg(phoneInfo);
			if(!BasicResp.isSuccess(resp)){
				return JSONObject.toJSONString(resp);
			}
			//保存授信信息
			ApplyOrder applyOrder = new ApplyOrder();
			
			applyOrder.setCustMngPhone(phone);
			applyOrder.setLicenseNo(licenseNo);
			applyOrder.setMerchantName(merchantName);
			applyOrder.setProductCode(ProductEnum.P_300002.getProductCode());
			
			String orderNo = GenerateIdsUtil.generateId(appConfig.getAppIp());
			applyOrder.setOrderNo(orderNo);
			applyOrder.setRegisterPhone(SeesionUtils.getData().getPhone());
			applyOrder.setRemark("");
			applyOrder.setStatus("00");
			orderService.insertApplyOrder(applyOrder);
			
			//提交授信申请 组装大数url
			String url = bdFConfig.getBdUrl();
			String userName= SeesionUtils.getData().getPhone();
			String channel = bdFConfig.getApiKey();
			Long time =System.currentTimeMillis();
			logger.info("sign params :"+"userName= "+ userName+"ApiSecret="+bdFConfig.getApiSecret()+"time="+time);
			String sign=Hashing.sha256().hashString(userName+bdFConfig.getApiSecret()+time,StandardCharsets.UTF_8).toString();
			
			
			StringBuffer redicretUrl = new StringBuffer(url);
			redicretUrl.append("username="+userName);
			redicretUrl.append("&channel="+channel);
			redicretUrl.append("&time="+time);
			redicretUrl.append("&sign="+sign);
			redicretUrl.append("&fullCompanyName="+merchantName);
			redicretUrl.append("&creditCode="+licenseNo);
			redicretUrl.append("&applicationNum="+orderNo);
			redicretUrl.append("&pageFlag="+bdFConfig.getApplyPageFlag());
			
//			String sign=Hashing.sha256().hashString(userName+bdFConfig.getApiKey()+time, StandardCharsets.UTF_8).toString();
//	 		String redicretUrl = url+"username="+userName+"&channel="+channel+"&time="+time+"&sign="
//	 				+sign+"&fullCompanyName="+merchantName+"&creditCode="+licenseNo+"&applicationNum="+orderNo
//	 				+"&pageFlag="+bdFConfig.getApplyPageFlag();
	 		logger.info("bdf url :"+redicretUrl.toString());
 		
 			Map<String,Object> map =new HashMap<>();
 			map.put("redirect", redicretUrl);
 			map.put("code", "000000");
 			map.put("message", "保存成功");
 			
			return JSONObject.toJSONString(map);
		} catch (Exception e) {
			logger.error("跳转报错信息"+e);
			return "common/error";
		}
		
	}
	
	
	
	@RequestMapping(value="/test",method=RequestMethod.GET)
	@ResponseBody
	public String test(HttpServletRequest request,HttpServletResponse response){
		//http://10.2.202.143:8196//bdfpreloan/loan/test?licenseNo=1111111111111&merchantName=测试
		String licenseNo = request.getParameter("licenseNo");//社会统一信用码
		String merchantName = request.getParameter("merchantName");//商户名
		
		//提交授信申请 组装大数url
		String url = bdFConfig.getBdUrl();
		String userName= "18712387792";
		String channel = bdFConfig.getApiKey();
		String time =new Timestamp(System.currentTimeMillis()).toString();
		String orderNo = GenerateIdsUtil.generateId(appConfig.getAppIp());
		
		String sign=Hashing.sha256().hashString(userName+bdFConfig.getApiKey()+time, StandardCharsets.UTF_8).toString();
 		String redicretUrl = url+"username="+userName+"$channel="+channel+"&time="+time+"&sign="
 				+sign+"&fullCompanyName="+merchantName+"&creditCode="+licenseNo+"&applicationNum="+orderNo
 				+"&pageFlag="+bdFConfig.getApplyPageFlag();
 		logger.info("bdf url :"+redicretUrl);
 		JSONObject json = new JSONObject();
 		json.put("redicretUrl", redicretUrl);
 		return JSONObject.toJSONString(json);
	}

	
}
